<template>
  <div class="database_wrap" :key="key">
    <div class="mainBox" ref="tableBox">
      <div class="mainLeft">
        <div class="top">
          <div class="tabs_box">
            <div class="tabs_box_header">
              {{ currTabItem.tabName }}
            </div>
          </div>
          <div
            class="bin_tabs"
            style="height: calc(100% - 35px); background: rgba(0, 0, 0, 0.7)"
          >
            <div id="line_container" style="width: 100%; height: 40%"></div>
            <div
              id="hot_container"
              ref="hot_container"
              style="width: 100%; height: 60%"
            ></div>
            <!-- <div class="title">时域折线图</div> -->
          </div>
        </div>

        <div class="bottom">
          <div class="infoLabel">
            <div class="result-title">计算结果</div>
            <el-button class="bin_button result-btn" @click="clickExport">
              导出
            </el-button>
          </div>
          <div
            class="tables"
            v-show="
              tableInfos && Array.isArray(tableInfos) && tableInfos.length > 0
            "
          >
            <el-tabs v-model="activeName" type="card" @tab-click="clicktab">
              <el-tab-pane
                v-for="(item, index) in tableInfos"
                :key="index"
                :label="item.tableName"
                :name="item.tableName"
              >
                <div
                  v-if="!item.tableHeader.length"
                  style="
                    height: 30px;
                    width: 100%;
                    border: 1px solid #02fff4;
                    color: #fff;
                    text-align: center;
                    line-height: 30px;
                  "
                >
                  无检测结果
                </div>
                <el-table
                  v-else
                  id="calculation_results_table"
                  :data="item.tableData"
                  empty-text="无检测结果"
                  style="width: 100%"
                  class="bin_table"
                  :border="true"
                  :fit="true"
                  max-height="300"
                >
                  <el-table-column
                    resizable
                    v-for="(v, i) in item.tableHeader"
                    :key="i"
                    :prop="v"
                    :label="v"
                  >
                    <template slot-scope="scope">
                      <div
                        v-if="v == '时间(s)'"
                        @click="clickBottomInfo(scope.$index, scope.row)"
                        style="
                          cursor: pointer;
                          display: block;
                          width: 100%;
                          height: 100%;
                        "
                        :title="scope.row[v]"
                      >
                        {{ scope.row[v] }}
                      </div>
                      <div
                        v-else
                        style="display: block; width: 100%; height: 100%"
                        :title="scope.row[v]"
                      >
                        {{ scope.row[v] }}
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </div>
      <div class="mainRight">
        <el-form
          ref="form"
          :model="form"
          label-position="left"
          label-width="155px"
        >
          <div class="base_info"></div>
          <div class="output_set">
            <div class="title_label">
              <span>参数设置</span>
            </div>
            <div class="info_box">
              <el-form-item label="文件">
                <el-button
                  v-if="!fileId"
                  class="bin_button"
                  size="small"
                  @click="selectFileShow = true"
                >
                  选择文件
                </el-button>
                <el-input
                  :disabled="false"
                  title="点击切换"
                  v-else
                  :value="formFileName"
                  @focus="selectFileShow = true"
                ></el-input>
              </el-form-item>
              <el-form-item
                v-for="(item, index) in inputParams"
                :label="item.variableChineseName"
                :key="index"
              >
                <el-input
                  class="bin_input"
                  v-model="form[item.variableChineseName]"
                  placeholder="请输入参数"
                ></el-input>
              </el-form-item>
              <el-form-item label="频率分辨率（Hz）">
                <el-input
                  class="bin_input"
                  disabled
                  v-model="newFrequencyResolution"
                ></el-input>
              </el-form-item>
            </div>
          </div>
          <div class="edit_btns">
            <el-button class="bin_button" size="small" @click="startBtn">
              开始计算
            </el-button>
          </div>
        </el-form>
      </div>
    </div>

    <el-dialog
      v-zsdialogDrag
      :closeOnClickModal="false"
      class="bin_dialog"
      title="新增"
      :visible.sync="addFileModel"
      width="1000px"
    >
      <div class="addContent">
        <div class="addItem">
          <div class="addName">文件类型：</div>
          <div class="addInput">
            <el-radio-group class="addChekoutRaio" v-model="checkboxGroup">
              <el-radio
                v-for="item in checkboxGroupList"
                :key="item.value"
                :label="item.value"
              >
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </div>
        </div>
        <div class="addItem">
          <div class="addName">文件来源：</div>
          <div class="addInput">
            <el-radio-group class="addChekoutRaio" v-model="fileFromType">
              <el-radio :label="0">本地文件</el-radio>
              <el-radio :label="1">数据库</el-radio>
            </el-radio-group>
          </div>
        </div>
        <div class="addItem" v-if="!fileFromType">
          <div class="addName">文件打开：</div>
          <div class="addInput">
            <el-upload
              class="upload-demo"
              ref="upload"
              multiple
              :auto-upload="false"
              :show-file-list="false"
              :file-list="fileList"
              :http-request="uploadFn"
              action="https://jsonplaceholder.typicode.com/posts/"
              :on-change="changeFile"
            >
              <el-button class="bin_button" size="mini">选择文件</el-button>
            </el-upload>
          </div>
        </div>
        <div class="addItem" v-if="!fileFromType">
          <div class="addName">文件预览：</div>
          <div class="addInput">
            <el-table
              :border="true"
              ref="multipleTable1"
              :data="fileList"
              tooltip-effect="dark"
              style="width: 90%"
              height="165px"
              class="bin_table"
            >
              <el-table-column resizable type="selection" show-overflow-tooltip>
              </el-table-column>
              <el-table-column
                min-width="170"
                resizable
                label="文件名称"
                show-overflow-tooltip
              >
                <template slot-scope="scope">{{ scope.row.name }}</template>
              </el-table-column>
              <el-table-column
                min-width="170"
                resizable
                prop="type"
                label="文件类别"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column
                min-width="170"
                resizable
                prop="size"
                label="文件大小"
                show-overflow-tooltip
              >
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div class="addItem" v-if="fileFromType">
          <el-table
            :border="true"
            ref="multipleTable2"
            :data="fileList2"
            tooltip-effect="dark"
            style="width: 90%"
            height="165px"
            class="bin_table"
          >
            <el-table-column resizable type="selection" show-overflow-tooltip>
            </el-table-column>
            <el-table-column
              min-width="170"
              resizable
              label="文件名称"
              show-overflow-tooltip
            >
              <template slot-scope="scope">{{
                scope.row.文件名称 || "-"
              }}</template>
            </el-table-column>
            <el-table-column
              min-width="170"
              resizable
              prop="文件格式"
              label="文件格式"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              min-width="170"
              resizable
              prop="文件大小"
              label="文件大小"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              min-width="170"
              resizable
              prop="采样率"
              label="采样率"
              show-overflow-tooltip
            >
            </el-table-column>
          </el-table>
        </div>
        <div class="btnContent">
          <el-button
            class="bin_button"
            size="small"
            @click="cancelFileUpload(false)"
          >
            取消
          </el-button>
          <el-button class="bin_button" size="small" @click="submitUpload">
            确定
          </el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      v-zsdialogDrag
      :closeOnClickModal="false"
      class="bin_dialog noPadding_dialog"
      title="选择文件"
      :visible.sync="selectFileShow"
      width="1000px"
      top="5vh"
    >
      <div class="itemList">
        <el-button
          class="bin_button"
          icon="el-icon-circle-plus"
          size="small"
          style="margin-bottom: 10px"
          @click="addFile(true)"
        >
          新增
        </el-button>
        <div
          :class="['listitem', { act: fileId === item.id }]"
          v-for="item in allFileList"
          :key="item.id"
          @click="selectFile(item)"
        >
          <div class="fileName">{{ item?.fileName }}</div>
          <div class="fileInfo">
            <div class="infoItem">
              <span>长度：</span> <span> {{ item?.fileLength }}</span>
            </div>
            <div class="infoItem">
              <span>大小：</span> <span> {{ item?.fileSize }}</span>
            </div>
            <div class="infoItem">
              <span>采样率：</span>
              <span> {{ item?.samplingRate }}(Hz)</span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      v-zsdialogDrag
      :closeOnClickModal="true"
      class="bin_dialog dialog-1000"
      title="频谱图"
      @close="closedispose"
      :visible.sync="centerChartShow"
      top="10vh"
      width="800px"
    >
      <div id="center_container" style="width: 100%; height: 250px"></div>
    </el-dialog>
    <!-- 导出弹窗 -->
    <el-dialog
      v-zsdialogDrag
      title="导出"
      :visible.sync="daochuDialogFlag"
      :closeOnClickModal="false"
      class="bin_dialog dialog-1000"
      width="50%"
      top="10vh"
    >
      <export-calculate
        v-if="daochuDialogFlag"
        :tabName="activeName"
        :taskId="currTabItem.taskId"
        @close="daochuDialogFlag = false"
      ></export-calculate>
    </el-dialog>
  </div>
</template>
<script>
import * as echarts from "echarts";
import { Loading, Notification } from "element-ui";
import { mapState } from "vuex";
import { calculateFrequencyResolution } from "@/utils/utils.js";
import exportCalculate from "@/components/exportCalculate.vue";

let lastUpdateTime = 0;
export default {
  name: "Analysis",
  components: { exportCalculate },
  data() {
    return {
      key: "1",
      centerChartShow: false,
      selectFileShow: false, // 控制选择文件的弹窗显隐
      xhrrequest: null, // 可以控制请求取消的 xhr
      imgList: "",
      algorithmId: "",
      allFileList: [],
      addFileModel: false,
      fileFromType: 0, // 上传文件时的文件来源，0 本地  1 数据库
      checkboxGroup: "1",
      checkboxGroupList: [
        {
          label: "WAV",
          value: "1",
        },
      ],
      fileId: "",
      inputParams: [],
      outParams: [],
      fileList: [],
      pageSize: 10,
      total: 100,
      xAxis: [],
      yAxis: [],
      tableInfos: [],
      activeName: "first",
      myChartLine: null,
      echartData: [],
      amplitudeData: [],
      lineChart: null,
      aaaZoomDate: {},
      xData: null,
      xMax: 0,
      xMin: 0,
      hotChart: null,
      formFileName: "",
      frequencyResolution: null,
      formFileId: "",
      props: { value: "typeId", label: "name" },
      chartType: [],
      form: {},
      range: {
        sampleSize: 10000,
        x1: null,
        x2: null,
        y1: null,
        y2: null,
      },
      initHotParams: {},
      hotParams: {},
      hotHeight: 0,
      xaxisMax: 0,
      xaxisMin: 0,
      newFrequencyResolution: null, //新的频率分辨率
      samplingRate: null, //采样率
      daochuDialogFlag: false, //导出弹窗显隐
    };
  },
  computed: {
    ...mapState({
      currTabItem: (state) => state.currTabItem,
    }),
  },

  watch: {
    fileId: {
      deep: true,
      immediate: true,
      handler(val) {
        if (val) {
          this.tableInfos = [];
          if (this.hotChart) {
            this.hotChart.dispose();
            this.hotChart = null;
          }
          this.getLineResult();
        }
      },
    },
    addFileModel: {
      deep: true,
      handler: function (val) {
        if (val) {
          this.getXXXXTableListFn();
        } else {
          this.checkboxGroup = "1";
          this.fileFromType = 0;
          this.fileList = [];
          this.fileList2 = [];
        }
      },
    },
    newFrequencyResolution: {
      deep: true,
      immediate: true, // 立即触发一次
      handler: function (newVal, oldVal) {
        // console.log("newFrequencyResolution1===", newVal, oldVal);
        if (newVal == null) {
          this.newFrequencyResolution =
            newVal || this.$store.state.newFrequencyResolutionInStore;
        }
        // console.log(
        //   "newFrequencyResolution2===",
        //   this.$store.state.newFrequencyResolutionInStore
        // );
        // console.log("newFrequencyResolution3===", this.newFrequencyResolution);
      },
    },
  },
  beforeDestroy() {
    this.$bus.$off("getdata");
  },
  created() {
    // console.log(this.$route, "created");
    this.$bus.$on("getdata", (rerender) => {
      this.getTabData(false, rerender);
    });
    // 获取所有文件
    this.getAllFiles();
    this.getTabData(true, true);
  },
  mounted() {
    this.hotHeight =
      this.$refs.hot_container.getBoundingClientRect().height - 100;
  },
  beforeRouteUpdate(to, from, next) {
    let t = this.$route.query.t;
    if (t) {
      this.key = t;
    }
    this.initializeData();
    next();
  },
  beforeDestroy() {
    this.$store.commit("SETCURRTABITEM", {});
    this.destroyChart();
    this.$store.commit("SET_NEW_FREQUENCY_RESOLUTION", null);
    // 移除事件监听
    document.removeEventListener("mousemove", this.onDrag);
    document.removeEventListener("mouseup", this.endDrag);
  },
  methods: {
    async getTabData(_, rerender) {
      if (rerender && this.lineChart) {
        this.lineChart.dispose();
        this.lineChart = null;
      }
      if (this.hotChart) {
        this.hotChart.dispose();
        this.hotChart = null;
      }
      // 如果从算法管理进来，没有参数列表
      if (!this.currTabItem.userInputParams && this.currTabItem.algorithmId) {
        await this.getParamsNew();
      } else {
        // 如果是从
        let inputParamsArray = [];
        const form = {};
        for (let i = 0; i < this.currTabItem.userInputParams.length; i++) {
          inputParamsArray.push({
            variableChineseName:
              this.currTabItem.userInputParams[i]["参数名称"],
            defaultValue: this.currTabItem.userInputParams[i]["参数值"],
          });
          form[this.currTabItem.userInputParams[i]["参数名称"]] =
            this.currTabItem.userInputParams[i]["参数值"];
        }
        this.form = JSON.parse(JSON.stringify(form));

        this.inputParams = inputParamsArray;
      }

      // 如果有文件信息
      if (rerender && this.currTabItem.fileId && this.currTabItem.fileName) {
        if (this.fileId == this.currTabItem.fileId) {
          this.tableInfos = [];
          if (this.hotChart) {
            this.hotChart.dispose();
            this.hotChart = null;
          }
          this.getLineResult();
        } else {
          this.fileId = this.currTabItem.fileId;
          this.formFileName = this.currTabItem.fileName;
        }
      }
      // console.log("this.currTabItem==", this.currTabItem);

      if (this.currTabItem.taskId) {
        // console.log("this.currTabItem.taskId==", this.currTabItem.taskId);
        this.getHotResult();
      } else {
        this.tableInfos = [];
      }
    },
    initializeData() {
      this.key = "1";
      this.centerChartShow = false;
      this.selectFileShow = false;
      this.xhrrequest = null;
      this.imgList = "";
      this.algorithmId = "";
      this.allFileList = [];
      this.addFileModel = false;
      this.fileFromType = 0;
      this.checkboxGroup = "1";
      this.checkboxGroupList = [
        {
          label: "WAV",
          value: "1",
        },
      ];
      this.fileId = "";
      this.inputParams = [];
      this.outParams = [];
      this.fileList = [];
      this.pageSize = 10;
      this.total = 100;
      this.xAxis = [];
      this.yAxis = [];
      this.tableInfos = [];
      this.activeName = "first";
      this.myChartLine = null;
      this.echartData = [];
      this.amplitudeData = [];
      this.lineChart = null;
      this.aaaZoomDate = {};
      this.xData = null;
      this.xMax = 0;
      this.xMin = 0;
      this.hotChart = null;

      this.formFileName = "";
      this.frequencyResolution = null;
      this.formFileId = "";
      this.props = { value: "typeId", label: "name" };
      this.chartType = [];
      this.form = {};
      this.range = {
        sampleSize: 10000,
        x1: null,
        x2: null,
        y1: null,
        y2: null,
      };
      this.initHotParams = {};
      this.hotParams = {};

      this.getTabData(true, true);
      // console.log(this.$route, "initializeData");
    },
    closedispose() {
      if (this.centerChart) {
        this.centerChart.dispose();
        this.centerChart = null;
      }
    },
    // 获取时域折线图数据
    getLineResult(paramsValue) {
      if (this.lineChart) {
        this.lineChart.dispose();
        this.lineChart = null;
      }
      let id = this.fileId;
      let params = {};
      if (paramsValue) {
        params = paramsValue;
      } else {
        params = {
          importFileId: id,
        };
      }
      // 拿到折线图的值  赋值渲染图
      this.$api.getTimeDomainMap(params).then((res) => {
        const { code, result } = res;
        if (code == 200) {
          if (!result) {
            if (this.lineChart) {
              this.lineChart.dispose();
              this.lineChart = null;
            }
          } else {
            this.amplitudeData = result?.amplitudePerSecond || [];
            this.xaxisMax = result.xaxisMax;
            this.xaxisMin = result.xaxisMin;
            const timeData = this.amplitudeData.map((item) => item[0]);
            const amplitudeDataValues = this.amplitudeData.map(
              (item) => item[1]
            );

            this.initLineChart(timeData, amplitudeDataValues);
            this.lineChart.resize();
          }
        }
      });
    },
    initLineChart(xData, yData) {
      if (this.lineChart) {
        this.lineChart.off("datazoom");
      }
      if (!this.lineChart) {
        this.lineChart = echarts.init(
          document.getElementById("line_container"),
          null,
          {
            renderer: "canvas", // 开启 Canvas 渲染模式
            locale: "zh",
          }
        );
      }

      var option = {
        tooltip: {
          show: true,
          trigger: "axis",

          borderColor: "#fff", // 设置边框颜色
          borderWidth: 1, // 设置边框宽度
          textStyle: {
            // color: '#fff', // 设置文字颜色
            fontSize: 16, // 设置字体大小
            fontWeight: "bold", // 设置字体粗细
          },
          formatter: (params) => {
            var relVal =
              '<div style="text-align:left;padding:5px;">' +
              '<span style="color:#FF6347;">振幅:</span> ' +
              params[0].data +
              "<br/>" +
              '<span style="color:#4682B4;">时间:</span> ' +
              this.lineFormatData(params[0].axisValue) +
              "</div>";
            return relVal;
          },
        },
        brush: {
          toolbox:
            this.currTabItem.tabName === "DEMON" ||
            this.currTabItem.tabName === "LOFAR"
              ? ["lineX", "clear"]
              : [],
          xAxisIndex: 0,
          brushStyle: {
            borderWidth: 1,
            color: "rgba(2, 255, 244,0.2)",
            borderColor: "rgba(2, 255, 244,0.8)",
          },
        },
        toolbox: {
          feature: {
            // dataZoom: {
            //   show: true,
            // },
            brush: {
              show:
                this.currTabItem.tabName === "DEMON" ||
                this.currTabItem.tabName === "LOFAR",
              type: ["lineX"],
              title: {
                lineX: "横向选择",
              },
              iconStyle: {
                borderColor: "rgba(2, 255, 244,0.8)",
              },
            },
            restore: {
              title: "还原",
              iconStyle: {
                borderColor: "#02fff4",
              },
            },
          },
        },
        xAxis: {
          type: "category",
          data: xData,
          name: "时间 (s)",
          boundaryGap: false,
          axisLabel: {
            color: "#fff",
            // 初始间隔值，可以根据需要调整
            // interval: Math.floor(xData.length / (_this.chongzhi ? 1 : 30)) || 1,
            rotate: 0, // 标签倾斜45度显示
            formatter: (duration) => {
              return this.lineFormatData(duration);
            },
          },

          nameTextStyle: {
            color: "#fff",
            fontSize: 16,
          },
        },
        yAxis: {
          // type: "value",
          name: "振幅",
          type: "value",
          axisLabel: {
            color: "#fff",
            formatter: "{value}\n",
          },
          nameTextStyle: {
            color: "#fff",
            fontSize: 16,
          },
        },
        dataZoom: [
          {
            type: "slider",
            xAxisIndex: 0,
            filterMode: "none",
            id: "1",
          },
          {
            type: "slider",
            yAxisIndex: 0,
            filterMode: "none",
            id: "2",
          },
          {
            type: "inside",
            xAxisIndex: 0,
            filterMode: "none",
            id: "3",
          },
          // {
          //   type: "inside",
          //   yAxisIndex: 0,
          //   filterMode: "none",
          //   id: "4",
          // },
        ],
        series: [
          {
            name: "振幅",
            type: "line", // 设置为折线图
            data: yData,
            smooth: false, // 设置为false，取消平滑曲线
            lineStyle: {
              width: 3, // 设置折线宽度
              color: "#46da97", // 设置折线颜色
            },
            progressive: 1000,
            progressiveThreshold: 3000,
            animation: false,
            itemStyle: {
              color: "#fff",
            },
            showSymbol: false, //禁止显示数据点,解决datazoom拖动会卡顿
            large: true,
          },
        ],
        grid: {
          top: 40,
          left: 150,
          right: 110,
          containLabel: false,
        },
      };

      this.lineChart.setOption(option);
      // 1秒是节流的间隔时间，你可以根据需要调整
      // 监听 dataZoomed 事件

      this.lineChart.getZr().on("click", (params) => {
        const pointInPixel = [params.offsetX, params.offsetY];
        // 判断给定的点是否在指定的坐标系
        if (this.lineChart.containPixel("grid", pointInPixel)) {
          const xIndex = this.lineChart.convertFromPixel(
            { seriesIndex: 0 },
            pointInPixel
          )[0];
          const option = this.lineChart.getOption(); // 获取当前内容
          if (option.xAxis[0].data[xIndex]) {
            this.getCenterChartResult(option.xAxis[0].data[xIndex]);
            this.centerChartShow = true;
          }
        }
      });
      // console.log("this.currTabItem.tabName======", this.currTabItem.tabName);
      this.lineChart.on("datazoom", (event) => {
        // console.log("lineChart datazoom", event);
        if (this.chongzhi) {
          // this.getHotResult("a");
          this.getHotResult();
          this.getLineResult();
          // console.log("同时调数据======", this.currTabItem.tabName);
          this.chongzhi = false;
          return;
        }

        // 拖拉x轴
        if (event.dataZoomId == 1) {
          if (!event.isInauthentic) {
            // // 假设 event 是从 ECharts dataZoom 事件中获取的
            // const startPercent = event.start;
            // const endPercent = event.end;
            // const dataLength = xData.length;

            // // 计算起始和结束索引
            // const startIndex = Math.round((startPercent / 100) * (dataLength - 1));
            // const endIndex = Math.round((endPercent / 100) * (dataLength - 1));

            // // 获取实际的数据范围
            // const zoomedDataArray = xData.slice(startIndex, endIndex + 1);
            // console.log(
            //   startPercent,
            //   endPercent,
            //   dataLength,
            //   startIndex,
            //   endIndex,
            //   zoomedDataArray,
            // );

            if (this.currTabItem.tabName === "DEMON") {
              this.hotChart &&
                this.hotChart.dispatchAction({
                  type: "dataZoom",
                  // 这里的参数根据实际情况调整
                  dataZoomIndex: 1,
                  start: event.start,
                  end: event.end,
                  isInauthentic: 1,
                });
            } else {
              // console.log("滑轮滚动x轴======", event.start, event.end);

              this.hotChart &&
                this.hotChart.dispatchAction({
                  type: "dataZoom",
                  // 这里的参数根据实际情况调整
                  dataZoomIndex: 0,
                  start: event.start,
                  end: event.end,
                  isInauthentic: 1,
                });
            }
          }
        } else if (event.batch instanceof Array && event.batch.length) {
          // 滑轮滚动x轴
          if (event.batch[0].dataZoomId == "3") {
            const item = event.batch[0];
            if (this.currTabItem.tabName === "DEMON") {
              this.hotChart &&
                this.hotChart.dispatchAction({
                  type: "dataZoom",
                  // 这里的参数根据实际情况调整
                  dataZoomIndex: 1,
                  start: item.start,
                  end: item.end,
                  isInauthentic: 1,
                });
            } else {
              this.hotChart &&
                this.hotChart.dispatchAction({
                  type: "dataZoom",
                  // 这里的参数根据实际情况调整
                  dataZoomIndex: 0,
                  start: item.start,
                  end: item.end,
                  isInauthentic: 1,
                });
            }
          }
        }
      });
      this.lineChart.on("brushEnd", (params) => {
        if (params.areas instanceof Array && params.areas.length) {
          let [start, end] = params.areas[0].coordRange;
          this.$set(this.range, "x1", start);
          this.$set(this.range, "x2", end);
        }
      });
      this.lineChart.on("brushselected", (params) => {
        if (!params.batch[0].areas.length) {
          this.$set(this.range, "x1", null);
          this.$set(this.range, "x2", null);
        }
      });
    },
    lineFormatData(duration) {
      return this.lineFormatData1(duration / 1000);
    },
    lineFormatData1(seconds, noms) {
      // 获取整数部分和小数部分
      let integerPart = Math.floor(seconds);
      let decimalPart = Math.round((seconds - integerPart) * 1000) / 1000; // 保留三位小数

      // 计算分钟和秒
      let minutes = Math.floor(integerPart / 60);
      let secs = integerPart % 60;

      // 格式化分钟、秒和毫秒部分
      let formattedMinutes = String(minutes).padStart(2, "0");
      let formattedSecs = String(Math.floor(secs)).padStart(2, "0");
      let formattedDecimalPart = decimalPart.toFixed(3).slice(2); // 去掉整数部分，只保留小数部分
      if (noms) {
        // 组合成最终格式
        return `${formattedMinutes}:${formattedSecs}`;
      } else {
        // 组合成最终格式
        return `${formattedMinutes}:${formattedSecs}.${formattedDecimalPart}`;
      }
    },
    // 获取热力图的数据
    getHotResult() {
      this.initHotParams = {
        taskId: this.currTabItem.taskId,
        x1: null,
        x2: null,
        y1: null,
        y2: null,
      };
      this.$api.queryAlgorithmResult(this.initHotParams).then((res) => {
        const { code, result } = res;
        if (
          code === 200 &&
          this.currTabItem.taskId === this.initHotParams.taskId
        ) {
          const {
            data,
            dataMax,
            dataMin,
            xMax,
            xMin,
            yAxis,
            frequencyResolution,
            timeResolution,
            tableInfos,
          } = result;
          this.xMax = xMax;
          this.xMin = xMin;
          this.yAxis = yAxis;
          this.frequencyResolution = frequencyResolution;
          this.timeResolution = timeResolution;

          if (tableInfos) {
            this.tableInfos = tableInfos;
            this.activeName = tableInfos[0].tableName;
          } else {
            this.tableInfos = [];
          }
          this.$nextTick(() => {
            if (data instanceof Array && data?.length) {
              let tableData = [];
              if (this.currTabItem.tabName === "DEMON") {
                tableData = data.map((e) => {
                  return [e[1], e[0] - xMin, e[2]];
                });
                this.initHotChartDemon(xMin, xMax, dataMin, dataMax, tableData);
                this.hotChart.resize();
              } else {
                tableData = data.map((e) => {
                  return [e[0] - xMin, e[1], e[2]];
                });
                this.initHotChart(xMin, xMax, dataMin, dataMax, tableData);
                this.hotChart.resize();
              }

              setTimeout(() => {
                if (
                  this.currTabItem.tabName == "LOFAR" ||
                  this.currTabItem.tabName == "信号检测" ||
                  this.currTabItem.tabName == "参数估计"
                ) {
                  this.hotChart &&
                    this.hotChart.dispatchAction({
                      type: "dataZoom",
                      batch: [
                        {
                          dataZoomIndex: 0,
                          start: 57.78,
                          end: 58.87,
                          isInauthentic: 1,
                        },
                        {
                          dataZoomIndex: 1,
                          start: 0,
                          end: 50,
                          isInauthentic: 1,
                        },
                      ],
                    });
                  this.lineChart &&
                    this.lineChart.dispatchAction({
                      type: "dataZoom",
                      batch: [
                        {
                          dataZoomIndex: 0,
                          start: 57.78,
                          end: 58.87,
                          isInauthentic: 1,
                        },
                        {
                          dataZoomIndex: 1,
                          start: 0,
                          end: 100,
                          isInauthentic: 1,
                        },
                      ],
                    });
                } else if (this.currTabItem.tabName == "DEMON") {
                  this.hotChart &&
                    this.hotChart.dispatchAction({
                      type: "dataZoom",
                      batch: [
                        {
                          dataZoomIndex: 0,
                          start: 0,
                          end: 45,
                          isInauthentic: 1,
                        },
                        {
                          dataZoomIndex: 1,
                          start: 0,
                          end: 100,
                          isInauthentic: 1,
                        },
                      ],
                    });
                  this.lineChart &&
                    this.lineChart.dispatchAction({
                      type: "dataZoom",
                      batch: [
                        {
                          dataZoomIndex: 0,
                          start: 0,
                          end: 100,
                          isInauthentic: 1,
                        },
                        {
                          dataZoomIndex: 1,
                          start: 0,
                          end: 100,
                          isInauthentic: 1,
                        },
                      ],
                    });
                } else if (this.currTabItem.tabName == "信号识别") {
                }
              }, 500);
            }
          });
        }
        // if (code === 500) {
        //   this.$message({
        //     message: res.message,
        //     type: "error",
        //   });
        // }
      });
    },
    initHotChart(xmin, xmax, min, max, tabledata) {
      if (!this.hotChart) {
        const chartDom = document.getElementById("hot_container");
        this.hotChart = echarts.getInstanceByDom(chartDom);
        this.hotChart = echarts.init(chartDom, null, {
          renderer: "canvas", // 开启 Canvas 渲染模式
          locale: "zh",
        });
      } else {
        this.hotChart.dispose();
        this.hotChart = null;
      }
      let maxxxx = Math.max(...tabledata.map((e) => e[0]));
      // console.log(maxxxx);

      let xData = [];

      const xMaxValue = Math.floor(xmax);

      for (let i = xmin; i <= xMaxValue; i++) {
        xData.push(i);
      }

      const option = {
        tooltip: {
          show: true,
          formatter: (params) => {
            let x1 = params.data[0];
            let y1 = params.data[1];
            let z1 = params.data[2];
            if (this.currTabItem.tabName == "DEMON") {
              y1 = Math.floor(y1 * this.frequencyResolution * 100) / 100;
            }
            y1 = y1 * this.frequencyResolution;
            // console.log(params);

            return `${y1}(Hz): ${z1}(db)`;
          },
        },
        grid: {
          top: 40,
          left: 150,
          right: 110,
          containLabel: false,
        },
        xAxis: {
          name: "时间 (s)",
          type: "category",
          data: xData,
          axisLine: {
            lineStyle: {
              color: "#fff",
            },
          },
          axisLabel: {
            // interval: 9
            formatter: (duration) => {
              return this.lineFormatData1(duration * this.timeResolution);
            },
          },
        },
        yAxis: {
          name: "(Hz)",
          type: "category",
          data: this.yAxis,
          axisLine: {
            lineStyle: {
              color: "#fff",
            },
          },
          axisLabel: {
            // interval: 9
            formatter: (value) => {
              if (this.currTabItem.tabName == "DEMON") {
                // 计算结果
                let result = value * this.frequencyResolution;
                // 强制保留两位小数，不进行四舍五入
                return Math.floor(result * 100) / 100;
              }
              return value * this.frequencyResolution;
            },
          },
          minInterval: 100, // 设置最小间隔为100
        },
        toolbox: {
          feature: {
            restore: {
              iconStyle: {
                borderColor: "#02fff4",
              },
            },
          },
        },
        dataZoom: [
          {
            type: "slider",
            xAxisIndex: 0,
            filterMode: "none",
            id: "1",
            realtime: false,
          },
          {
            type: "slider",
            yAxisIndex: 0,
            filterMode: "none",
            id: "2",
            realtime: false,
          },
          {
            type: "inside",
            xAxisIndex: 0,
            filterMode: "none",
            id: "3",
            realtime: false,
          },
        ],
        visualMap: {
          type: "continuous", // 使用连续型视觉映射
          min: min,
          max: max,
          calculable: true,
          realtime: false,
          itemHeight: this.hotHeight,
          precision: 4,
          text: null,
          inverse: false,
          // range: [min + (max - min) / 2, max - (max - min) / 20],
          textStyle: {
            color: "#fff",
            // color: "transparent",
          },
          hoverLink: true,
          left: 10,
          bottom: 60,

          // "#87CEEB",
          // "#FF0000",
          // "#00FFFF",
          // "#FFFF00",
          // "#4B0082",
          // "#228B22",
          // "#FF4500",
          // "#0000FF",
          // "#FFB6C1",
          // "#6B8E23",
          // "#8A2BE2",
          // "#FFBF00",
          // "#006400",
          // "#FF69B4",
          // "#228B22",
          // "#B22222",
          // "#DA70D6",
          // "#66CDAA",
          // "#FF7F50",
          // "#000080",
          inRange: {
            color: ["#0000fF", "#00ffFF", "#00FF00", "#FFFF00", "#FF0000"],
          },
          outOfRange: {
            color: ["#000"],
          },
        },
        series: [
          {
            name: "信号",
            type: "heatmap",
            data: tabledata,
            emphasis: {
              itemStyle: {
                borderColor: "#333",
                borderWidth: 1,
              },
            },
            progressive: 1000,
            progressiveThreshold: 3000,
            animation: false,
            itemStyle: {
              color: "#fff",
            },
            showSymbol: false, //禁止显示数据点,解决datazoom拖动会卡顿
            large: true,
          },
        ],
      };
      option && this.hotChart.setOption(option);
      this.hotChart.off("datazoom");
      this.hotChart.on("datazoom", (event) => {
        // console.log("hotchart datazoom", event);

        // 拖拉x轴
        if (event.dataZoomId == 1) {
          if (!event.isInauthentic) {
            this.lineChart &&
              this.lineChart.dispatchAction({
                type: "dataZoom",
                // 这里的参数根据实际情况调整
                dataZoomIndex: 0,
                start: event.start,
                end: event.end,
                isInauthentic: 1,
              });
          }
        } else if (event.dataZoomId == 2) {
          // 拖拉y轴;
          if (!event.isInauthentic) {
            this.lineChart &&
              this.lineChart.dispatchAction({
                type: "dataZoom",
                // 这里的参数根据实际情况调整
                dataZoomIndex: 1,
                start: event.start,
                end: event.end,
                isInauthentic: 1,
              });
          }
        } else {
          // 滑轮滚动x轴
          if (!event.isInauthentic) {
            event.batch.forEach((res, index) => {
              this.lineChart &&
                this.lineChart.dispatchAction({
                  type: "dataZoom",
                  // 这里的参数根据实际情况调整
                  dataZoomIndex: index,
                  start: res.start,
                  end: res.end,
                  isInauthentic: 1,
                });
            });
          }
        }
        if (!event.noUpdate) {
          this.updateHotEcharts(event);
        }
      });
    },
    initHotChartDemon(xmin, xmax, min, max, tabledata) {
      if (!this.hotChart) {
        const chartDom = document.getElementById("hot_container");
        this.hotChart = echarts.getInstanceByDom(chartDom);
        this.hotChart = echarts.init(chartDom, null, {
          renderer: "canvas", // 开启 Canvas 渲染模式
          locale: "zh",
        });
      } else {
        this.hotChart.dispose();
        this.hotChart = null;
      }

      let maxxxx = Math.max(...tabledata.map((e) => e[0]));
      // console.log("initHotChartDemon==", maxxxx);

      let yDaat = [];

      const xMaxValue = Math.floor(xmax);

      for (let i = xmin; i <= xMaxValue; i++) {
        yDaat.push(i);
      }
      const option = {
        tooltip: {
          show: true,
        },
        grid: {
          top: 40,
          left: 150,
          right: 110,
          containLabel: false,
        },
        yAxis: {
          type: "category",
          data: yDaat,
          name: "时间 (s)",
          axisLine: {
            lineStyle: {
              color: "#fff",
            },
          },
          axisLabel: {
            // interval: 9
            formatter: (duration) => {
              return this.lineFormatData1(duration * this.timeResolution, true);
            },
          },
        },
        xAxis: {
          type: "category",
          data: this.yAxis,
          name: "(Hz)",
          axisLine: {
            lineStyle: {
              color: "#fff",
            },
          },
          axisLabel: {
            // interval: 9
            formatter: (value) => {
              // 计算结果
              let result = value * this.frequencyResolution;
              // 强制保留两位小数，不进行四舍五入
              return Math.floor(result * 100) / 100;
            },
          },
          minInterval: 100,
        },
        toolbox: {
          feature: {
            restore: {
              iconStyle: {
                borderColor: "#02fff4",
              },
            },
          },
        },
        dataZoom: [
          {
            type: "slider",
            xAxisIndex: 0,
            filterMode: "none",
            id: "1",
            realtime: false,
          },
          {
            type: "slider",
            yAxisIndex: 0,
            filterMode: "none",
            id: "2",
            realtime: false,
          },
          {
            type: "inside",
            yAxisIndex: 0,
            filterMode: "none",
            id: "3",
            realtime: false,
          },
        ],
        visualMap: {
          type: "continuous", // 使用连续型视觉映射
          min: min,
          max: max,
          calculable: true,
          realtime: false,
          itemHeight: this.hotHeight,
          precision: 4,
          text: null,
          textStyle: {
            color: "#fff",
            // color: "transparent",
          },
          left: 10,
          bottom: 60,
          inRange: {
            color: ["#0000ff", "#f350cf", "#f9e234", "#fbfcfb"],
          },
        },
        series: [
          {
            name: "信号",
            type: "heatmap",
            data: tabledata,
            emphasis: {
              itemStyle: {
                borderColor: "#333",
                borderWidth: 1,
              },
            },
            progressive: 1000,
            progressiveThreshold: 3000,
            animation: false,
            itemStyle: {
              color: "#fff",
            },
            showSymbol: false, //禁止显示数据点,解决datazoom拖动会卡顿
            large: true,
          },
        ],
      };
      option && this.hotChart.setOption(option);
      this.hotChart.off("datazoom");
      this.hotChart.on("datazoom", (event) => {
        // console.log("hotchart datazoom", event);

        // 拖拉x轴
        if (event.dataZoomId == 1) {
          // if (!event.isInauthentic) {
          //   this.lineChart &&
          //     this.lineChart.dispatchAction({
          //       type: "dataZoom",
          //       // 这里的参数根据实际情况调整
          //       dataZoomIndex: 0,
          //       start: event.start,
          //       end: event.end,
          //       isInauthentic: 1,
          //     });
          // }
        } else if (event.dataZoomId == 2) {
          // 拖拉y轴
          if (!event.isInauthentic) {
            this.lineChart &&
              this.lineChart.dispatchAction({
                type: "dataZoom",
                // 这里的参数根据实际情况调整
                dataZoomIndex: 0,
                start: event.start,
                end: event.end,
                isInauthentic: 1,
              });
          }
        } else {
          // 滑轮滚动y轴
          if (!event.isInauthentic) {
            event.batch.forEach((res, index) => {
              this.lineChart &&
                this.lineChart.dispatchAction({
                  type: "dataZoom",
                  // 这里的参数根据实际情况调整
                  dataZoomIndex: index,
                  start: res.start,
                  end: res.end,
                  isInauthentic: 1,
                });
            });
          }
        }
        if (!event.isInauthentic) {
          this.updateHotEchartsDemon();
        }
      });
    },

    updateHotEcharts(event) {
      // console.log("event:", event);
      // console.log("updateHotEcharts called by:", event?.type || "unknown");
      const now = Date.now();
      if (now - lastUpdateTime < 3000) return; // 限制每 500ms 执行一次
      lastUpdateTime = now;
      if (!this.hotChart) {
        var chartDom = document.getElementById("hot_container");
        this.hotChart = echarts.getInstanceByDom(chartDom); // 注意这里使用的是 getInstanceByDom 而不是 getEchartsInstance
        this.hotChart = echarts.init(chartDom, null, {
          renderer: "canvas", // 开启 Canvas 渲染模式
          locale: "zh",
        });
      }

      var rangeY = this.hotChart.getModel().getComponent("yAxis").axis
        .scale._extent;
      var rangeX = this.hotChart.getModel().getComponent("xAxis").axis
        .scale._extent;

      this.hotParams = {
        taskId: this.currTabItem.taskId,
        sampleSize: 10000,
        x1: rangeX[0] + this.xMin,
        x2: rangeX[1] + this.xMin,
        y1: rangeY[0],
        y2: rangeY[1],
      };

      try {
        if (this.xhrrequest) {
          this.xhrrequest.abort();
        }

        this.xhrrequest = new XMLHttpRequest();
        this.xhrrequest.open(
          "POST",
          `${this.$http.defaults.baseURL}/underwater-sound/dataAlgorithmsProcessing/queryAlgorithmResultData`
        );
        this.xhrrequest.setRequestHeader(
          "Authorization",
          `Bearer ${this.$store.state.token}`
        );
        this.xhrrequest.setRequestHeader("Content-Type", "application/json");
        this.xhrrequest.onreadystatechange = (e) => {
          if (
            this.xhrrequest.readyState === 4 &&
            this.xhrrequest.status === 200 &&
            this.currTabItem.taskId === this.hotParams.taskId
          ) {
            // 解析响应的 JSON 数据
            var responseData = JSON.parse(this.xhrrequest.responseText);
            const {
              code,
              result: {
                data,
                dataMax,
                dataMin,
                xMax,
                xMin,
                yAxis,
                frequencyResolution,
                timeResolution,
              },
            } = responseData;
            this.xMax = xMax;
            this.xMin = xMin;
            this.yAxis = yAxis;
            this.frequencyResolution = frequencyResolution;
            this.timeResolution = timeResolution;
            let tableData = data.map((e) => {
              return [e[0] - xMin, e[1], e[2]];
            });
            this.xMax = Math.floor(xMax);

            if (code == 200) {
              this.hotChart.setOption({
                visualMap: {
                  min: dataMin,
                  max: dataMax,
                },
                series: [
                  {
                    name: "信号",
                    type: "heatmap",
                    data: tableData,
                    emphasis: {
                      itemStyle: {
                        borderColor: "#333",
                        borderWidth: 1,
                      },
                    },
                    progressive: 2000,
                    animation: false,
                    large: true,
                  },
                ],
              });
            }
          }
        };
        this.xhrrequest.send(JSON.stringify(this.hotParams));
      } catch (error) {}
      // console.log("其他算法的热力图更新完毕");
    },
    updateHotEchartsDemon() {
      if (!this.hotChart) {
        var chartDom = document.getElementById("hot_container");
        this.hotChart = echarts.getInstanceByDom(chartDom); // 注意这里使用的是 getInstanceByDom 而不是 getEchartsInstance
        this.hotChart = echarts.init(chartDom, null, {
          renderer: "canvas", // 开启 Canvas 渲染模式
          locale: "zh",
        });
      }

      var rangeY = this.hotChart.getModel().getComponent("yAxis").axis
        .scale._extent;
      var rangeX = this.hotChart.getModel().getComponent("xAxis").axis
        .scale._extent;

      let query = {
        taskId: this.currTabItem.taskId,
        sampleSize: 10000,
        x1: rangeY[0] + this.xMin,
        x2: rangeY[1] + this.xMin,
        y1: rangeX[0],
        y2: rangeX[1],
      };

      try {
        if (this.xhrrequest) {
          this.xhrrequest.abort();
        }

        this.xhrrequest = new XMLHttpRequest();
        this.xhrrequest.open(
          "POST",
          `${this.$http.defaults.baseURL}/underwater-sound/dataAlgorithmsProcessing/queryAlgorithmResultData`
        );
        this.xhrrequest.setRequestHeader(
          "Authorization",
          `Bearer ${this.$store.state.token}`
        );
        this.xhrrequest.setRequestHeader("Content-Type", "application/json");
        this.xhrrequest.onreadystatechange = (e) => {
          if (
            this.xhrrequest.readyState === 4 &&
            this.xhrrequest.status === 200
          ) {
            // 解析响应的 JSON 数据
            var responseData = JSON.parse(this.xhrrequest.responseText);
            const {
              code,
              result: {
                data,
                dataMax,
                dataMin,
                xMax,
                xMin,
                yAxis,
                frequencyResolution,
                timeResolution,
              },
            } = responseData;

            this.xMax = xMax;
            this.xMin = xMin;
            this.yAxis = yAxis;
            this.frequencyResolution = frequencyResolution;
            this.timeResolution = timeResolution;

            let tableData = data.map((e) => {
              return [e[1], e[0] - xMin, e[2]];
            });
            this.xMax = Math.floor(xMax);
            if (code == 200) {
              this.hotChart.setOption({
                visualMap: {
                  min: dataMin,
                  max: dataMax,
                },
                series: [
                  {
                    name: "信号",
                    type: "heatmap",
                    data: tableData,
                    emphasis: {
                      itemStyle: {
                        borderColor: "#333",
                        borderWidth: 1,
                      },
                    },
                    progressive: 2000,
                    animation: false,
                    large: true,
                  },
                ],
              });
            }
          }
        };
        this.xhrrequest.send(JSON.stringify(query));
      } catch (error) {}
    },
    /**
     * 点击标签事件处理函数
     *
     * @param e 事件对象，VueComponent

     */
    clicktab(e) {
      // console.log("clicktab==", this.currTabItem.tabName);
      let data = [];
      if (
        this.currTabItem.tabName == "信号检测" ||
        this.currTabItem.tabName == "LOFAR"
      ) {
        data = this.tableInfos[0].tableData.map((e) => {
          return {
            xAxis: Math.ceil(e["时间(s)"] * 1000),
          };
        });
        // console.log("data==", data);
      }
      if (this.currTabItem.tabName == "参数估计") {
        data = this.processTimeArray(this.tableInfos[0].tableData);
        // console.log("data==", data);
      }
      if (data.length) {
        this.lineChart.setOption({
          series: [
            {
              markLine: {
                silent: true, // 不响应和触发鼠标事件
                lineStyle: { color: "#fff", width: 2 },
                label: {
                  formatter: (duration) => {
                    // console.log(duration.value);
                    // console.log(this.lineFormatData(duration.value));
                    return this.lineFormatData(duration.value);
                  },
                },
                data: data,
              },
            },
          ],
        });
      }
    },
    // 处理参数估计--时间段
    processTimeArray(arr) {
      const result = [];
      arr.forEach((item) => {
        const [start, end] = item["时间(s)"].split("-"); // 按"-"分开
        const startTime = { xAxis: Math.ceil(start.replace("s", "")) * 1000 }; // 去掉"s"并乘以1000
        const endTime = { xAxis: Math.ceil(end.replace("s", "")) * 1000 }; // 同上
        result.push(startTime, endTime); // 向上取整并添加到结果数组
      });
      return result;
    },
    /**
     * 点击底部信息
     *
     * @param {number} i - 表格的第i行，从0开始
     * @param {Object} e - 事件对象，包含点击位置的信息，表头和当前行的值
     */
    clickBottomInfo(i, e) {
      // 需要点击table表中的"时间(s)"字段标线这一行：检测算法(信号检测) 检测识别估计算法(参数估计)

      // 检测算法(信号检测):点击number1 显示SignalTime中的值对应x轴画一条线  竖线
      // 检测识别估计算法(参数估计):点击信号序号1显示SignalTime中的多少到多少值对应x轴画两条线  竖线-区域
      let data = [];
      // 点击echart图下的table表
      // 更新标记点和标记线
      // console.log("this.currTabItem.tabName==", this.currTabItem.tabName);
      if (
        this.currTabItem.tabName == "信号检测" ||
        this.currTabItem.tabName == "LOFAR"
      ) {
        //单条线赋值
        // console.log("信号检测==", i, e);
        data = [
          // 在特定x轴值处绘制竖线   进一法取值
          {
            xAxis: Math.ceil(e["时间(s)"] * 1000),
            lineStyle: { color: "#00ff00", width: 2 },
          },
        ];
        let alt = e["时间(s)"].split(".")[0];
        // console.log("信号检测alt==", alt);
        let dataValue = [];
        let paramsValue = [];
        if (alt) {
          dataValue = [
            (Number(alt) / this.xMax) * 100,
            ((Number(alt) + 1) / this.xMax) * 100,
          ];
          paramsValue = [
            (Number(alt) / this.xaxisMax) * 1000 * 100,
            ((Number(alt) + 1) / this.xaxisMax) * 1000 * 100, //ceil
          ];
        }
        if (dataValue && dataValue.length > 0) {
          this.hotChart &&
            this.hotChart.dispatchAction({
              type: "dataZoom",
              dataZoomIndex: 0,
              start: dataValue[0] / this.timeResolution,
              end: dataValue[1] / this.timeResolution,
              isInauthentic: 1,
            });
          // console.log("信号检测dataValue==", dataValue);
        }
        if (paramsValue && paramsValue.length > 0) {
          this.lineChart &&
            this.lineChart.dispatchAction({
              type: "dataZoom",
              dataZoomIndex: 0,
              start: paramsValue[0],
              end: paramsValue[1],
              isInauthentic: 1,
            });
          // console.log("信号检测paramsValue==", paramsValue);
        }
      }
      // 参数估计
      if (this.currTabItem.tabName == "参数估计") {
        //多条线赋值
        let arr = [];
        // console.log("参数估计==", i, e);

        if (e["时间(s)"] && e["时间(s)"].indexOf("-") !== -1) {
          arr = e["时间(s)"].split("-");
        }
        // console.log("arr==", arr);

        arr.forEach((item, index) => {
          // 在特定x轴值处绘制竖线   进一法取值
          let value = {
            xAxis: Math.ceil(item.replace("s", "") * 1000),
            lineStyle: { color: "#00ff00", width: 2 },
          };
          data.push(value);
        });
        // console.log("data==", data);
        if (e["时间(s)"] && this.activeName == "检测识别估计结果表") {
          let alt = e["时间(s)"].split("-")[0].split(".")[0];
          // console.log("alt==", alt);
          let alt1 = e["时间(s)"].split("-")[1].split(".")[0];
          // console.log("alt1==", alt1);
          let dataValue = [];
          let paramsValue = [];
          if (alt) {
            dataValue = [
              (Number(alt) / this.xMax) * 100,
              ((Number(alt1) + 1) / this.xMax) * 100,
            ];
            paramsValue = [
              (Number(alt) / this.xaxisMax) * 1000 * 100,
              ((Number(alt1) + 1) / this.xaxisMax) * 1000 * 100, //ceil
            ];
          }
          if (dataValue && dataValue.length > 0) {
            this.hotChart &&
              this.hotChart.dispatchAction({
                type: "dataZoom",
                dataZoomIndex: 0,
                start: dataValue[0] / this.timeResolution,
                end: dataValue[1] / this.timeResolution,
                isInauthentic: 1,
              });
            console.log("dataValue==", dataValue);
          }
          if (paramsValue && paramsValue.length > 0) {
            this.lineChart &&
              this.lineChart.dispatchAction({
                type: "dataZoom",
                dataZoomIndex: 0,
                start: paramsValue[0],
                end: paramsValue[1],
                isInauthentic: 1,
              });
            // console.log("paramsValue==", paramsValue);
          }
        }
      }
      if (data.length) {
        this.lineChart.setOption({
          series: [
            {
              markLine: {
                silent: true, // 不响应和触发鼠标事件
                lineStyle: { color: "#00ff00", width: 2 },
                label: {
                  formatter: (duration) => {
                    return this.lineFormatData(duration.value);
                  },
                },
                data: data,
              },
            },
          ],
        });

        // console.log("if==", data);
      }
    },
    getCenterChartResult(start) {
      let for2m = this.inputParams.map((e) => {
        return {
          参数名称: e.variableChineseName,
          参数值: this.form[e.variableChineseName],
        };
      });
      const data = {
        algorithmId: this.currTabItem.algorithmId,
        importFileId: this.fileId,
        interceptStartTime: start,
        inputParamsValues: for2m,
      };
      this.$api.getCenterLineChartData(data).then((res) => {
        const { code } = res;
        if (code == 200) {
          const {
            result: { xAxis, yAxis },
          } = res;
          this.$nextTick(() => {
            this.renderCenterChart(xAxis, yAxis);
          });
        }
      });
    },
    renderCenterChart(xData, yData) {
      this.centerChart = echarts.init(
        document.getElementById("center_container"),
        null,
        {
          renderer: "canvas", // 开启 Canvas 渲染模式
          locale: "zh",
        }
      );
      const option = {
        xAxis: {
          type: "category",
          name: "(hz)",
          boundaryGap: false,
          data: xData,
          axisLine: {
            position: "bottom",
            onZero: false,
            lineStyle: {
              color: "#fff",
            },
          },
          position: "bottom",
        },
        yAxis: {
          type: "value",
          name: "(db)",

          axisLabel: {
            color: "#fff",
            formatter: "{value}\n",
          },
          nameTextStyle: {
            color: "#fff",
            fontSize: 16,
          },
        },
        toolbox: {
          feature: {
            restore: {
              iconStyle: {
                borderColor: "#02fff4",
              },
            },
          },
        },
        dataZoom: [
          {
            type: "slider",
            xAxisIndex: 0,
            filterMode: "filter",
            id: "1",
          },
          {
            type: "slider",
            yAxisIndex: 0,
            filterMode: "filter",
            id: "2",
          },
          {
            type: "inside",
            xAxisIndex: 0,
            filterMode: "none",
            id: "3",
          },
        ],
        grid: {
          top: 30,
          right: 80,
          bottom: 70,
        },
        series: [
          {
            data: yData,
            type: "line",
            smooth: true,
          },
        ],
      };

      this.centerChart.setOption(option);
    },

    // 获取不知名table-list
    async getXXXXTableListFn() {
      let params = {
        unstructuredTableType: "wav",
      };
      let res = await this.$api.getXXXXTableListApi(params);
      this.fileList2 = res?.result || [];
    },
    // 通过接口去获取参数列表
    async getParamsNew() {
      let params = {
        algorithmId: this.currTabItem.algorithmId,
      };
      const res = await this.$api.getParams(params);
      let input = res.result.filter((e) => e.isInputOrOutput == 0);
      let output = res.result.filter((e) => e.isInputOrOutput == 1);
      input = input.sort((a, b) => a.inputOrOutputSort - b.inputOrOutputSort);
      output = output.sort((a, b) => a.inputOrOutputSort - b.inputOrOutputSort);
      this.inputParams = input;

      const form = {};
      for (let i = 0; i < input.length; i++) {
        form[input[i].variableChineseName] = input[i].defaultValue;
      }
      this.form = JSON.parse(JSON.stringify(form));
      this.outParams = output;
    },
    // 销毁图表
    destroyChart() {
      if (this.hotChart) {
        this.hotChart.dispose();
        this.hotChart = null;
      }
      if (this.lineChart) {
        this.lineChart.dispose();
        this.lineChart = null;
      }
    },
    // 显示新增文件弹窗
    addFile() {
      this.addFileModel = true;
    },
    // 上传时更换文件
    changeFile(files, fileList) {
      for (let i = 0; i < fileList.length; i++) {
        const file = fileList[i];
        this.$set(this.fileList, i, { ...file, type: file.raw.type });
      }
    },
    // 上传时选择文件
    uploadFn() {
      var data = new FormData();
      let multipartFiles = this.$refs.multipleTable.selection.map((item) => {
        return item.raw;
      });
      data.append("file", multipartFiles);
      this.$api
        .addTempFile({ multipartFiles: data, fileSource: this.fileFromType })
        .then((res) => {});
    },
    // 框选后 开始计算
    selectStart() {
      Loading.service({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });

      let for2m = this.inputParams.map((e) => {
        return {
          参数名称: e.variableChineseName,
          参数值: this.form[e.variableChineseName],
        };
      });
      // 如果选择的时候是LOFAR
      this.$api
        .executeAlgorithm({
          algorithmId: this.currTabItem.algorithmId,
          importFileId: this.fileId,
          inputParamsValues: for2m,
        })
        .then((res) => {
          if (res.code == 200) {
            // 提示用户
            this.$message({
              message: res.result,
              type: "success",
            });
          } else {
            this.$message({
              message: res.result,
              type: "info",
            });
          }
        })
        .catch((err) => {
          let loadingInstance = Loading.service({});
          this.$nextTick(() => {
            // 以服务的方式调用的 Loading 需要异步关闭
            loadingInstance.close();
          });
        });
    },
    // 开始计算
    startBtn() {
      if (!this.fileId) {
        // 提示用户选择文件
        this.$message({
          message: "请从选择一个文件",
          type: "warning",
        });
      } else {
        this.loading = this.$loading({
          lock: true,
          text: "Loading",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });

        let for2m = this.inputParams.map((e) => {
          return {
            参数名称: e.variableChineseName,
            参数值: this.form[e.variableChineseName],
          };
        });
        // 如果选择的时候是LOFAR
        console.log("for2m===", for2m);
        const windowWidth = for2m.find(
          (item) => item["参数名称"] === "窗口宽度(s)"
        )?.["参数值"];
        // console.log("计算结果===", this.samplingRate, windowWidth);

        this.newFrequencyResolution = calculateFrequencyResolution(
          this.$store.state.samplingRate,
          windowWidth
        );

        this.$api
          .executeAlgorithm({
            algorithmId: this.currTabItem.algorithmId,
            importFileId: this.fileId,
            inputParamsValues: for2m,
            interceptStartTime: this.range.x1,
            interceptEndTime: this.range.x2,
          })
          .then((res) => {
            if (res.code == 200) {
              Notification.closeAll();
              Notification.success({
                title: "正在计算",
                message: res.result,
                position: "top-right",
                offset: 80,
                duration: 0,
              });
              // this.$message({
              //   message: res.result,
              //   type: "success",
              // });
            } else {
              this.$message({
                message: res.result,
                type: "info",
              });
            }
          })
          .catch((err) => {
            let loadingInstance = Loading.service({});
            this.$nextTick(() => {
              // 以服务的方式调用的 Loading 需要异步关闭
              loadingInstance.close();
            });
          });
      }
    },

    // 为当前算法选择文件
    selectFile(val) {
      this.fileId = val.id;
      this.formFileName = val.fileName;
      this.samplingRate = val.samplingRate;
      this.$store.commit("SET_SAMPLING_RATE", this.samplingRate);
    },
    // 取消上传 隐藏文件上传窗口
    cancelFileUpload() {
      this.addFileModel = false;
    },
    // 提交选择好的文件上传
    submitUpload() {
      let selected = null;
      if (this.fileFromType === 0) {
        selected = this.$refs.multipleTable1.selection;
      } else if (this.fileFromType === 1) {
        selected = this.$refs.multipleTable2.selection;
      }
      if (selected.length) {
        let formData = new FormData();
        if (this.fileFromType === 0) {
          formData.append("importType", 0);
          selected.map((item) => {
            formData.append("fileDataList", item.raw);
          });
        } else if (this.fileFromType === 1) {
          formData.append("importType", 1);
          selected.map((item) => {
            formData.append("fileIdList", item.kid);
          });
        }
        this.$api.importData(formData).then(() => {
          this.addFileModel = false;
          this.getAllFiles();
        });
      } else {
        this.$message({
          message: "请选择数据",
          type: "warning",
        });
      }
    },
    // 获取所有文件列表
    getAllFiles() {
      this.$api.getImportFileList().then((res) => {
        if (res.code == 200) {
          this.allFileList = res.result.map((item) => {
            return item;
          });
        }
      });
    },
    // 为计算结果---的表头字段添加单位
    getLabel(value) {
      switch (value) {
        case "叶频":
          return "叶频 (Hz)";
        case "归一化强度":
          return "归一化强度";
        case "频率":
          return "频率 (Hz)";
        case "叶片数":
          return "叶片数 (个)";
        case "轴频":
          return "轴频 (Hz)";
        default:
          return value;
      }
    },
    // 导出数据
    clickExport() {
      this.daochuDialogFlag = true;
    },
  },
};
</script>
<style lang="scss" scoped>
.database_wrap {
  width: 100%;
  height: 100%;
  --head-title: 50px;

  .itemLefthead {
    width: 100%;
    display: flex;
    height: var(--head-title);
    background: rgba(2, 255, 244, 0.15);
    border-radius: 0px 0px 0px 0px;
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: 500;
    font-size: 20px;
    color: #fff;
    line-height: 59px;
    text-align: left;
    font-style: normal;
    text-transform: none;
    text-indent: 31px;
    position: relative;
    align-items: center;
    justify-content: space-between;

    &::before {
      width: 5px;
      height: 20px;
      background: #02fff4;
      border-radius: 0px 0px 0px 0px;
      position: absolute;
      left: 20px;
      top: 16px;
      content: "";
    }
  }

  .left {
    height: 100%;
    width: 20%;
    position: absolute;
    right: 0;

    .itemLeft {
      width: 100%;
      height: 100%;
      background: rgba(2, 82, 107, 0.6);
      border: 1px solid #02fff4;
    }
  }

  .itemList {
    width: 100%;
    padding: 20px;
    box-sizing: border-box;
    height: calc(100% - 50px);
    overflow: scroll;

    .listitem {
      width: 100%;
      box-sizing: border-box;
      cursor: pointer;
      border-radius: 3px;
      color: #fff;
      padding: 16px;
      margin-bottom: 10px;
      background-color: #072f46;
      // border: 1px solid transition;
      border: 1px solid #02fff4;

      // box-shadow: inset 0px 0px 15px 1px rgba(2, 255, 244, 0.5);
      &.act {
        border: 1px solid #02fff4;
        box-shadow: inset 0px 0px 15px 1px #02fff4;
      }

      .fileName {
        font-family: Source Han Sans CN, Source Han Sans CN;
        font-weight: 500;
        font-size: 18px;
        color: #fff;
        line-height: 32px;
        padding-left: 34px;
        box-sizing: border-box;
        position: relative;

        &::before {
          content: "";
          position: absolute;
          left: 0;
          background-image: url("../../../assets/file.png");
          background-repeat: no-repeat;
          background-position: center;
          background-size: 32px 32px;
          width: 32px;
          height: 32px;
        }
      }

      .fileInfo {
        font-family: Source Han Sans CN, Source Han Sans CN;
        font-weight: 400;
        font-size: 16px;
        color: #fff;
        text-align: left;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .infoItem {
          font-family: Source Han Sans CN, Source Han Sans CN;
          font-weight: 500;
          font-size: 16px;
          color: #fff;
          line-height: 32px;
          display: flex;
          justify-content: space-between;
        }
      }
    }
  }

  height: 100%;
  width: calc(100%);

  .mainBox {
    // --martop: 5px;
    // margin-top: var(--martop);
    // height: calc(100% - 50px - var(--martop));
    height: 100%;
    display: flex;

    .mainLeft {
      width: calc(73% - 10px);
      // height: 100%;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .resulttext {
        font-size: 16px;
        color: #fff;
      }

      .top {
        width: 100%;
        height: 70%;
        overflow: hidden;
        box-sizing: border-box;
        border: 1px solid #02fff4;
        background: rgba(2, 82, 107, 0.6);
        position: relative;

        .tabs_box {
          display: flex;
          justify-content: flex-start;
          align-items: center;
          border-bottom: 1px solid #02fff4;
          color: #fff;
          height: 35px;
          .tabs_box_header {
            height: 100%;
            line-height: 35px;
            border: 1px solid #02fff4;
            box-sizing: border-box;
            padding: 0 20px;
          }
        }

        ::v-deep .bin_tabs {
          // height: calc(100% - 40px);
          height: 100%;

          .title {
            font-size: 18px;
            color: #fff;
            margin-left: 15px;
            margin-top: -20px;
          }

          .el-tabs__header {
            border: none;
            height: 0;
            display: none;

            .el-tabs__nav {
              border: none;
            }
          }

          .el-tabs__content {
            height: calc(100% - 40px);
            background: rgba(0, 0, 0, 0.7);

            .el-tab-pane {
              height: 100%;
              overflow-y: scroll;
            }
          }
        }

        .dialogBtn {
          position: absolute;
          top: 1px;
          right: 5px;
          z-index: 99;
        }
      }

      .bottom {
        width: 100%;
        height: 30%;
        overflow: auto;
        border: 1px solid #02fff4;
        background: rgba(2, 82, 107, 0.6);
        box-sizing: border-box;
        padding: 0 20px;

        .infoLabel {
          width: 100%;
          font-family: Source Han Sans CN, Source Han Sans CN;
          font-weight: 500;
          font-size: 20px;
          color: #ffffff;
          padding: 10px;
          line-height: 26px;
          position: relative;
          box-sizing: border-box;
          padding-left: 16px;

          &::before {
            content: "";
            position: absolute;
            left: 0;
            top: 13px;
            width: 5px;
            height: 20px;
            background: #02fff4;
          }
          .result-title {
            width: 140px;
          }
          .result-btn {
            height: 30px;
            line-height: 10px;
            position: absolute;
            right: 0;
            top: 10px;
          }
        }

        .tables {
          width: 100%;
          ::v-deep .el-tabs__nav {
            width: 100%;
            display: flex;
            justify-content: space-around;
            align-items: center;

            .el-tabs__item {
              flex: 1;
              color: #fff;
              text-align: center;
              font-size: 16px;
              font-weight: 600;
            }

            .is-active {
              color: #01f2f4;
            }
          }
        }

        .infoLine {
          font-family: Source Han Sans CN, Source Han Sans CN;
          font-weight: 400;
          font-size: 18px;
          color: #ffffff;
          line-height: 26px;
          width: calc(100% - 140px);
          display: flex;
          justify-content: space-between;
          align-items: center;
        }
      }
    }

    .mainRight {
      width: 27%;
      height: 100%;
      border: 1px solid #02fff4;
      background: rgba(2, 82, 107, 0.6);
      box-sizing: border-box;
      padding: 10px;
      margin-left: 10px;
      overflow: auto;

      .jieguo {
        width: 100%;
        height: 50px;
        background: #009fb1;
        font-family: Source Han Sans CN, Source Han Sans CN;
        font-weight: 500;
        font-size: 20px;
        color: #ffffff;
        line-height: 50px;
        text-align: center;
        margin-bottom: 10px;
      }

      .collBox {
      }
    }
  }

  .btn {
    width: auto;
    height: 40px;
    padding-top: 10px;
    padding-bottom: 10px;
    box-shadow: inset 0px 0px 15px 1px #02fff4;
    background-color: transparent;
    outline: none;
    border: 1px solid #02fff4;
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: 400;
    font-size: 18px;
    color: #fff;
    font-style: normal;
    text-transform: none;
    cursor: pointer;
    position: relative;
  }

  .addContent {
    padding: 20px;

    .addItem {
      display: flex;
      align-items: center;
      margin-bottom: 32px;
      width: 100%;

      .addInput {
        margin-left: 10px;
        width: 100%;
      }

      .addChekoutRaio {
        margin-left: 10px;

        ::v-deep .el-radio {
          font-family: Source Han Sans CN, Source Han Sans CN;
          font-weight: 400;
          font-size: 18px !important;
          color: #fff;
          line-height: 0px;
          text-align: left;
          font-style: normal;
          text-transform: none;
        }

        ::v-deep .el-radio__inner {
          background: inherit;
          border: 3px solid #02fff4;
          width: 18px;
          height: 18px;
        }

        ::v-deep .el-radio__inner::after {
          background-color: #02fff4;
          width: 10px;
          height: 10px;
        }

        ::v-deep .el-radio__input.is-checked + .el-radio__label {
          color: #02fff4;
        }
      }

      .addChekoutFile {
        border: 0;
        margin-right: 0;

        ::v-deep .el-checkbox__label {
          font-size: 18px !important;
          color: #fff !important;
        }

        ::v-deep .el-checkbox__inner {
          width: 22px;
          height: 22px;
          background: inherit !important;
          border: 1px solid #02fff4;
        }

        ::v-deep .is-checked {
          .el-checkbox__inner {
            &::after {
              box-sizing: content-box;
              content: "";
              background: #02fff4;
              height: 10px;
              left: 4px;
              position: absolute;
              top: 5px;
              width: 10px;
              transition: transform 0.15s ease-in 0.05s;
              transform-origin: center;
              transform: rotate(90deg) scaleY(1);
              border: 0 !important;
            }
          }
        }
      }
    }

    .exportInput {
      width: 90%;
      height: 40px;
      border-radius: 0px 0px 0px 0px;
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: 400;
      font-size: 16px;
      color: #fff;
      text-align: left;
      font-style: normal;
      text-transform: none;
      background: inherit;

      ::v-deep .el-input__inner::-moz-placeholder {
        color: #fff !important;
      }

      ::v-deep .el-input__inner::-webkit-input-placeholder {
        color: #fff !important;
      }

      ::v-deep .el-input__inner {
        background-color: inherit;
        border: 1px solid #02fff4;
        color: #fff;
      }

      ::v-deep .el-input-group__append {
        background: rgba(2, 255, 244, 0.1);
        border-radius: 0px 0px 0px 0px;
        border: 1px solid #02fff4;
        font-family: Source Han Sans CN, Source Han Sans CN;
        font-weight: 400;
        font-size: 16px;
        color: #02fff4;
        text-align: center;
        font-style: normal;
        text-transform: none;
        cursor: pointer;
      }
    }

    .addName {
      width: 90px;
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: 500;
      font-size: 18px;
      color: #fff;
      text-align: left;
      font-style: normal;
      text-transform: none;
      flex: 0 0 auto;
    }

    .ls {
      width: 170px;
    }

    .selectFile {
      width: 250px;
      height: 36px;
      background: #001b3c;
      box-shadow: inset 0px 0px 20px 1px #02fff4;
      border: 1px solid #02fff4;
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: 400;
      font-size: 16px;
      color: rgba(2, 255, 244, 1);
      line-height: 36px;
      text-align: left;
      font-style: normal;
      text-transform: none;
      opacity: 0.5;
      cursor: pointer;
      text-align: center;
    }
  }

  .btnContent {
    text-align: center;

    .host {
      float: right;
      height: 18px;
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: 400;
      font-size: 18px;
      color: #fff;
      line-height: 32px;
      margin-top: 10px;
      text-align: right;
    }
  }

  .noPadding_dialog {
    ::v-deep .el-dialog__body {
      padding: 0;
    }
  }

  ::v-deep .collBox {
    border: none;

    .el-collapse-item__header {
      padding-left: 16px;
      font-weight: 400;
      font-size: 18px;
      background: rgba(2, 255, 244, 0.1);
      color: #a2fffb;
      border: 1px solid #02fff4;
      margin-bottom: 10px;
    }

    .el-collapse-item__wrap {
      background-color: transparent;
      border-bottom: none;
      padding-left: 15px;
    }

    .infoBar {
      display: flex;
      justify-content: space-between;

      .label {
        width: 140px;
        font-family: Source Han Sans CN, Source Han Sans CN;
        font-weight: 500;
        font-size: 16px;
        color: #ffffff;
        line-height: 32px;
        text-align: left;
      }

      .value {
        width: calc(100% - 140px);
        text-align: left;
        font-family: Source Han Sans CN, Source Han Sans CN;
        font-weight: 400;
        font-size: 16px;
        color: #ccc;
        line-height: 32px;
      }
    }
  }
}

.edit_btns {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 30px;
  padding-bottom: 20px;
}

.title_label {
  background-color: rgba(2, 255, 244, 0.15);
  width: 100%;
  height: 50px;
  font-family: Source Han Sans CN, Source Han Sans CN;
  font-weight: 500;
  font-size: 18px;
  color: #fff;
  line-height: 50px;
  text-align: left;
  padding: 0 40px;
  display: flex;
  justify-content: space-between;
  box-sizing: border-box;
  align-items: center;
}

::v-deep .el-form-item__label {
  font-family: Source Han Sans CN, Source Han Sans CN;
  font-weight: 500;
  font-size: 18px;
  color: #fff;
}

.info_box,
.params_box,
.output_box {
  padding: 20px;
  padding-bottom: 0;
}

.paramsItem,
.outputItem {
  display: flex;
  justify-content: space-between;
  height: 100%;
  margin-bottom: 20px;

  .params_form_box,
  .output_form_box {
    width: calc(100% - 48px);

    .form_title {
      background-color: rgba(2, 255, 244, 0.1);
      height: 40px;
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: 500;
      font-size: 18px;
      color: #fff;
      line-height: 40px;
      display: flex;
      padding: 0 20px;
      box-sizing: border-box;
    }

    .miniform_box {
      background: rgba(2, 82, 107, 0.2);
      padding: 20px;
      box-sizing: border-box;

      .el-form-item {
        &:last-child {
          margin-bottom: 0;
        }
      }

      .line {
        text-align: center;
        color: #fff;
      }
    }
  }

  .del {
    cursor: pointer;
    width: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: rgba(12, 81, 99, 0.5);
  }
}
::v-deep #calculation_results_table {
  .el-table__cell {
    padding: 4px 0;
  }
  .el-table__body {
    border-collapse: collapse;
  }
}
</style>
